Now that you can iterate over a block of statements, the next related concept is how to control the flow of program execution. C# defines two simple constructs to alter the flow of your program, based on various contingencies:
First up is our good friend the if/else statement. Unlike in C and C++, however, the if/else statement in C# operates only on Boolean expressions, not ad hoc values such as -1 or 0. Given this, if/else statements typically involve the use of the C# operators shown in Table 3-7 in order to obtain a literal Boolean value.
Table 3-7. C# Relational and Equality Operators
C# Equality/Relational Operator | Example Usage | Meaning in Life |
---|---|---|
== | if(age == 30) | Returns true only if each expression is the same. |
!= | if("Foo" != myStr) | Returns true only if each expression is different. |
< > <= >= |
if(bonus < 2000) if(bonus > 2000) if(bonus <= 2000) if(bonus >= 2000) |
Returns true if expression A (bonus) is less than, greater than, less than or equal to, or greater than or equal to expression B (2000). |
Again, C and C++ programmers need to be aware that the old tricks of testing a condition for a value not equal to zero will not work in C#. Let�s say you want to see whether the string you are working with is longer than zero characters. You may be tempted to write
static void ExecuteIfElse() { // This is illegal, given that Length returns an int, not a bool. string stringData = "My textual data"; if(stringData.Length) { Console.WriteLine("string is greater than 0 characters"); } }
If you wish to make use of the String.Length property to determine truth or falsity, you need to modify your conditional expression to resolve to a Boolean.
// Legal, as this resolves to either true or false. if(stringData.Length > 0) { Console.WriteLine("string is greater than 0 characters"); }
An if statement may be composed of complex expressions as well and can contain else statements to perform more complex testing. The syntax is identical to C(++) and Java. To build complex expressions, C# offers an expected set of logical operators, as shown in Table 3-8.
Table 3-8. C# Logical Operators
Logical Operator | Example | Meaning in Life |
---|---|---|
&& | if(age == 30 && name == "Fred") | AND operator. Returns true if all expressions are true. |
|| | if(age == 30 || name == "Fred") | OR operator. Returns true if at least one expression is true. |
! | if(!myBool) | NOT operator. Returns true if false, or false if true. |
Note The && and || operators both "short circuit" when necessary. This means once a complex expression has been determined to be false, the remaining expressions will not be checked.
The other simple selection construct offered by C# is the switch statement. As in other C-based languages, the switch statement allows you to handle program flow based on a predefined set of choices. For example, the following Main() logic prints a specific string message based on one of two possible selections (the default case handles an invalid selection).
// Switch on a numerical value. static void ExecuteSwitch() { Console.WriteLine("1 [C#], 2 [VB]"); Console.Write("Please pick your language preference: "); string langChoice = Console.ReadLine(); int n = int.Parse(langChoice); switch (n) { case 1: Console.WriteLine("Good choice, C# is a fine language."); break; case 2: Console.WriteLine("VB: OOP, multithreading, and more!"); break; default: Console.WriteLine("Well...good luck with that!"); break; } }
Note C# demands that each case (including default) that contains executable statements have a terminating break or goto to avoid fall-through.
One nice feature of the C# switch statement is that you can evaluate string data in addition to numeric data. Here is an updated switch statement that does this very thing (notice we have no need to parse the user data into a numeric value with this approach).
static void ExecuteSwitchOnString() { Console.WriteLine("C# or VB"); Console.Write("Please pick your language preference: "); string langChoice = Console.ReadLine(); switch (langChoice) { case "C#": Console.WriteLine("Good choice, C# is a fine language."); break; case "VB": Console.WriteLine("VB: OOP, multithreading and more!"); break; default: Console.WriteLine("Well...good luck with that!"); break; } }
Source Code The IterationsAndDecisions project is located under the Chapter 3 subdirectory.
That wraps up your look at the looping and decision keywords of C#, and the common operators that are used to build complex statements. I�ve tried to keep this part of the chapter short and to the point, as I am assuming you have experience using similar keywords (if, for, switch, etc.) in your current programming language. If you require more information, look up the topic of interest within the .NET Framework 4.0 SDK Documentation.